package com.example.print.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.graphics.Typeface;
import android.graphics.Color;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.example.print.R;
import com.example.print.fragment.PrintCodeFragment;
import com.example.print.fragment.PrintPictureFragment;
import com.example.print.fragment.PrintTemplateFragment;
import com.example.print.fragment.PrintTextFragment;
import com.example.print.other.LanguageAdapter;
import com.google.android.material.tabs.TabLayout;
import com.panling.printapi.Printer;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private String TAG = "MainActivity";

    private Context context;
    private static String version = "";
    private AlertDialog mAlertDialog = null;
    private View mView;
    public Printer mPrinter;

    private TabLayout mTab;
    private ViewPager mViewPager;
    private DrawerLayout mDrawerLayout;
    private String[] arrayLanguage;
    private int setup_language;
    private boolean isNORMAL = true;//打印机是否正常
    private int printstatus = 0;//打印机状态返回值
    private boolean is_printing = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);
        initView();
        context = this;
        initActionBar();
        initViewPager();

        mView = View.inflate(getApplicationContext(), R.layout.dialog_layout, null);
        mAlertDialog = new AlertDialog.Builder(this)
                .setView(mView)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        mAlertDialog.cancel();
                    }
                }).create();

        mAlertDialog.setTitle(getString(R.string.PrintVersion));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu_setting, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.version) {
            if (TextUtils.isEmpty(version)) {
                mHandler.sendEmptyMessage(2);
            }
            Log.d(TAG, "getVersion...." + version);
            showPopup();
            return true;
        }
        if (item.getItemId() == R.id.SetLanguage) {
            mHandler.sendEmptyMessage(4);
            return true;
        }
        if (item.getItemId() == R.id.upgradeMcu) {
            Toast.makeText(context, R.string.Not_currently_open, Toast.LENGTH_SHORT).show();
            return false;
        }
        if (item.getItemId() == R.id.upgradeFont) {
            Toast.makeText(context, R.string.Not_currently_open, Toast.LENGTH_SHORT).show();
            return false;
        }
        if (item.getItemId() == R.id.Restore) {
            mHandler.sendEmptyMessage(3);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            int what = msg.what;

            if (what == 0) {    //update
                TextView tv = (TextView) mAlertDialog.findViewById(R.id.tv_dialog);
                if (TextUtils.isEmpty(version)) {
                    tv.setText(R.string.No_Version);
                    version = mPrinter.getVersion();
                } else {
                    tv.setText(" " + version);
                }
                Log.e(TAG, "showPopup.mHandler.....2." + mAlertDialog.isShowing() + "," + getClass());
                if (!mAlertDialog.isShowing()) {
                    mAlertDialog.show();
                }
            } else if (what == 1) {
                mAlertDialog.cancel();
            } else if (what == 2) {
                version = mPrinter.getVersion();
            } else if (what == 3) {
                mPrinter.restoreDefault();
                Toast.makeText(context, R.string.Restore_success, Toast.LENGTH_SHORT).show();
            }else if (what == 4) {
                showLanguageSelectionDialog();
            }
        }
    };

    private String getLanguageName_andsetup(int index) {
        switch (index) {
            case 0:
                setup_language = 0;
                return getString(R.string.United_States_Standard);
            case 1:
                setup_language = 2;
                return getString(R.string.Multilingual_West_Europe);
            case 2:
                setup_language = 3;
                return getString(R.string.Portugal);
            case 3:
                setup_language = 4;
                return getString(R.string.Canada_France);
            case 4:
                setup_language = 5;
                return getString(R.string.Germany_Germanic);
            case 5:
                setup_language = 6;
                return getString(R.string.West_Europe);
            case 6:
                setup_language = 7;
                return getString(R.string.Greek);
            case 7:
                setup_language = 8;
                return getString(R.string.Hebrew);
            case 8:
                setup_language = 9;
                return getString(R.string.East_Europe);
            case 9:
                setup_language = 10;
                return getString(R.string.Iran);
            case 10:
                setup_language = 11;
                return getString(R.string.Baltic_Sea);
            case 11:
                setup_language = 12;
                return getString(R.string.Japan);
            case 12:
                setup_language = 13;
                return getString(R.string.Korea);
            case 13:
                setup_language = 14;
                return getString(R.string.TR_China);
            case 14:
                setup_language = 15;
                return getString(R.string.SM_China);
            case 15:
                setup_language = 16;
                return getString(R.string.PC1251);
            case 16:
                setup_language = 17;
                return getString(R.string.Cyrillice);
            case 17:
                setup_language = 18;
                return getString(R.string.Latin2);
            case 18:
                setup_language = 19;
                return getString(R.string.West_Europe_2);
            case 19:
                setup_language = 20;
                return getString(R.string.Iceland);
            case 20:
                setup_language = 21;
                return getString(R.string.Russia);
            case 21:
                setup_language = 22;
                return getString(R.string.Bulgaria);
            case 22:
                setup_language = 23;
                return getString(R.string.Turkey);
            case 23:
                setup_language = 24;
                return getString(R.string.Arab);
            case 24:
                setup_language = 25;
                return getString(R.string.Greece);
            case 25:
                setup_language = 32;
                return getString(R.string.Thailand);
            case 26:
                setup_language = 33;
                return getString(R.string.Central_Europe);
            case 27:
                setup_language = 34;
                return getString(R.string.Cyrillic);
            case 28:
                setup_language = 35;
                return getString(R.string.Latin);
            case 29:
                setup_language = 36;
                return getString(R.string.Greek_2);
            case 30:
                setup_language = 37;
                return getString(R.string.Turkish);
            case 31:
                setup_language = 38;
                return getString(R.string.Hebrew_2);
            case 32:
                setup_language = 39;
                return getString(R.string.Arabic);
            case 33:
                setup_language = 40;
                return getString(R.string.Baltic);
            case 34:
                setup_language = 41;
                return getString(R.string.Vietnam);
            case 35:
                setup_language = 42;
                return getString(R.string.Kannada);
            default:
                setup_language = 0;
                return getString(R.string.United_States_Standard);
        }
    }


    private void showLanguageSelectionDialog() {
        String[] languages = getResources().getStringArray(R.array.arrayLanguage);
        int currentSelection = getSelectedLanguage();

        Log.e(TAG, "Print_get_current_Language = " + mPrinter.Print_get_current_Language());
        // 创建 ListView 并设置适配器
        ListView listView = new ListView(context);
        LanguageAdapter adapter = new LanguageAdapter(context, languages, currentSelection);
        listView.setAdapter(adapter);

        // 创建 AlertDialog
        AlertDialog dialog = new AlertDialog.Builder(context)
                .setView(listView)
                .create();

        // 设置点击事件：点击选项后立即保存设置并关闭对话框
        listView.setOnItemClickListener((parent, view, position, id) -> {
            saveSelectedLanguage(position);
            setLanguage(position);
            dialog.dismiss();
        });

        dialog.show();
    }




    // 设置语言方法
    private void setLanguage(int selectedIndex) {
        String languageName = getLanguageName_andsetup(selectedIndex);
        // 保存选择并更新语言逻辑
        saveSelectedLanguage(selectedIndex);
        // 发送设置语言的指令
        Log.e(TAG, "selectedIndex = " + selectedIndex + " setup_language= " + setup_language);
        mPrinter.Print_Setup_Language(setup_language);
    }


    private void saveSelectedLanguage(int index) {
        SharedPreferences preferences = context.getSharedPreferences("language_prefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt("selected_language_index", index);
        editor.apply();
    }

    private int getSelectedLanguage() {
        SharedPreferences preferences = context.getSharedPreferences("language_prefs", Context.MODE_PRIVATE);
        // 默认返回 0（可以改成默认语言索引）
        return preferences.getInt("selected_language_index", 0);
    }


    /**
     * 获取版本信息功能
     */
    private void showPopup() {
        Log.e(TAG, "showPopup.....1." + mAlertDialog.isShowing() + "," + getClass());
        mAlertDialog.show();
        Log.e(TAG, "showPopup.....2." + mAlertDialog.isShowing() + "," + getClass());
        mHandler.sendEmptyMessage(0);
    }

    private void initViewPager() {
        MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getSupportFragmentManager());

        List<Fragment> list = new ArrayList<>();
        list.add(new PrintTextFragment());
        list.add(new PrintCodeFragment());
        list.add(new PrintPictureFragment());
        list.add(new PrintTemplateFragment());

        adapter.setFragmentList(list);
        mTab.addTab(mTab.newTab());
        mTab.addTab(mTab.newTab());
        mTab.addTab(mTab.newTab());
        mTab.addTab(mTab.newTab());
        mViewPager.setAdapter(adapter);

        mTab.getTabAt(0).setText(R.string.TextPrint);
        mTab.getTabAt(1).setText(R.string.CodePrint);
        mTab.getTabAt(2).setText(R.string.PicturePrint);
        mTab.getTabAt(3).setText(R.string.TemplatePrint);

      //  arrayLanguage = getResources().getStringArray(R.array.arrayLanguage);
    }

    private void updateViewPager() {
        MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getSupportFragmentManager());

        List<Fragment> list = new ArrayList<>();
        list.add(new PrintTextFragment());
        list.add(new PrintCodeFragment());
        list.add(new PrintPictureFragment());
        list.add(new PrintTemplateFragment());

        adapter.setFragmentList(list);
        mTab.addTab(mTab.newTab());
        mTab.addTab(mTab.newTab());
        mTab.addTab(mTab.newTab());
        mTab.addTab(mTab.newTab());
        mViewPager.setAdapter(adapter);


        mTab.getTabAt(0).setText(R.string.Label_TextPrint);//标签文本打印
        mTab.getTabAt(1).setText(R.string.Label_CodePrint);//标签条码打印
        mTab.getTabAt(2).setText(R.string.Label_PicturePrint);//标签图片打印
        mTab.getTabAt(3).setText(R.string.Label_TemplatePrint);//标签样板打印

    }
    private void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("");
        if (actionBar != null) {
            // 设置ActionBar的自定义视图
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            actionBar.setCustomView(R.layout.custom_action_bar_buttons);

            final Button button1 = actionBar.getCustomView().findViewById(R.id.action_button1);
            final Button button2 = actionBar.getCustomView().findViewById(R.id.action_button2);
            button1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    initViewPager();
                    button1.setBackgroundResource(R.drawable.rounded_button_background_2);
                    button2.setBackgroundResource(R.drawable.rounded_button_background_3);
                    mPrinter.Black_label_Off();//关闭标签
                }
            });
            button2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateViewPager();
                    button1.setBackgroundResource(R.drawable.rounded_button_background);
                    button2.setBackgroundResource(R.drawable.rounded_button_background_4);
                    mPrinter.Black_label_On();//开启标签
                }
            });
        }
    }

    private void initView() {
        mTab = (TabLayout) findViewById(R.id.tab);
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mTab.setupWithViewPager(mViewPager);
    }

    @Override
    public void onResume() {
        super.onResume();

        try {
            mPrinter = Printer.getInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        new InitTask().execute();

        if (TextUtils.isEmpty(version)) {
            mHandler.sendEmptyMessageDelayed(2, 2 * 1000);
        }

        mPrinter.setPrinterStatusCallBack(new CallBack());
    }

    @Override
    public void onStop() {
        super.onStop();

        if (mPrinter != null) {
            mPrinter.free();
        }
        Log.d(TAG, "onStop...." + getClass());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            Log.e(TAG, "onKeyDown-....KEYCODE_BACK=BACK" + "," + getClass());
            if (mPrinter != null) {
                mPrinter.free();
            }
            finish();
            //System.exit(0);
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    protected class InitTask extends AsyncTask<String, Integer, Boolean> {
        ProgressDialog mypDialog;

        @Override
        protected Boolean doInBackground(String... params) {
            // TODO Auto-generated method stub
            return mPrinter.init();
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            mypDialog.cancel();
            if (!isNORMAL) {
                Toast.makeText(context, R.string.Printer_init_fail, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, R.string.Printer_init_success, Toast.LENGTH_SHORT).show();
                initParameter();
            }
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            mypDialog = new ProgressDialog(context);
            mypDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mypDialog.setMessage(getString(R.string.Printer_init));
            mypDialog.setCanceledOnTouchOutside(false);
            mypDialog.show();
        }
    }

    private int speed = 200;
    private void initParameter(){
        mPrinter.setFlowcontrol(1);//开启流控
        mPrinter.setPrintSpeed(speed);//设置打印速度,最大220
    }

    private static void notice_lackofpaper(final Context cont) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(cont);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setTitle(R.string.lackofpaper);
        builder.setPositiveButton(R.string.ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 退出
                    }
                });
        builder.show();
    }

    private static void notice_overhot(final Context cont) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(cont);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setTitle(R.string.PrintOverHot);
        builder.setPositiveButton(R.string.ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 退出
                    }
                });
        builder.show();
    }

    private static void notice_coveropen(final Context cont) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(cont);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setTitle(R.string.PrintCoverOpen);
        builder.setPositiveButton(R.string.ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 退出
                    }
                });
        builder.show();
    }
    private static void notice_nomessage(final Context cont) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(cont);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setTitle(R.string.PrintNoBack);
        builder.setPositiveButton(R.string.ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 退出
                    }
                });
        builder.show();
    }
    private static void notice_busy(final Context cont) {
        TextView textView = new TextView(cont);
        textView.setGravity(Gravity.CENTER);
        textView.setTypeface(null, Typeface.BOLD);
        textView.setTextSize(30);
        textView.setTextColor(Color.RED);
        textView.setText(R.string.PrintBusy);

        AlertDialog dialog = new AlertDialog.Builder(cont)
                .setIcon(android.R.drawable.ic_dialog_info)
               // .setTitle(R.string.PrintBusy)
                .setView(textView)
                .setCancelable(false) // 设置对话框不可以通过点击背景取消
                .show();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
            }
        },3 * 1000);  //延迟3秒执行
    }

    private class CallBack implements Printer.PrinterStatusCallBack {
        @Override
        public void message(Printer.PrinterStatus infoCode) {
            Log.e(TAG, "Thread CallBack...infoCode=" + infoCode);
            switch (infoCode) {
                case NORMAL://正常:
                    isNORMAL = true;
                    printstatus = 0;
                    setTitle(getString(R.string.app_name) + R.string.Normal);
                    break;
                case LEISURE:
                    isNORMAL = true;
                    printstatus = 1;
                    setTitle(getString(R.string.app_name) + R.string.Normal);
                    break;
                case UNLEISURED://打印机繁忙
                    isNORMAL = false;
                    printstatus = 10;
                    notice_busy(context);
                    break;
                case LACKOFPAPER://缺纸
                    isNORMAL = false;
                    printstatus = 3;
                    notice_lackofpaper(context);
                    break;
                case OVERHEATING://过热
                    isNORMAL = false;
                    printstatus = 4;
                    notice_overhot(context);
                    break;
                case PRESSUREAXISOPEN://仓盖已经打开
                    isNORMAL = false;
                    printstatus = 5;
                    notice_coveropen(context);
                    break;
                case NOMESSAGE://打印模块无信息返回
                    isNORMAL = false;
                    printstatus = 6;
                    notice_nomessage(context);
                    break;

            }
        }
    }

    public int GetPrinterStatus(){
        return printstatus;
    }
    public boolean IsPrinterNormal(){
        return isNORMAL;
    }
    public boolean get_is_printing(){
        return is_printing;
    }
    public void set_is_printing(boolean value){
        is_printing = value;
    }


}